<template>
  <div>
    <el-upload
      v-show="!isShowProgress"
      action="#"
      :http-request="onRequest"
      list-type="picture-card"
      :file-list="fileList"
      :class="{ display: fileList.length }"
      :on-remove="onRemove"
      :on-change="onChange"
      :on-preview="handlePictureCardPreview"
      :before-upload="beforeUpload"
      accept="image/jpeg, image/gif, image/png"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-progress v-if="isShowProgress" type="circle" :percentage="percentage" />
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
var cos = new COS({
  SecretId: 'AKIDgIejX4LL4WieJhoeEXZLq53kAJBnMeeR',
  SecretKey: 'XnmUw71e05tQffOs52j9IAk35qLYU9Yg'
})
export default {
  name: 'UploadImage',
  data() {
    return {
      fileList: [],
      dialogImageUrl: '',
      dialogVisible: false,
      currentUid: '',
      percentage: 0,
      isShowProgress: false
    }
  },

  created() {

  },

  methods: {
    onRemove(file, fileList) {
      this.fileList = fileList
    },
    onRequest(data) {
      cos.putObject({
        Bucket: 'hrsaas-hz-22-1307760757', /* 必须 */
        Region: 'ap-shanghai', /* 存储桶所在地域，必须字段 */
        Key: data.file.name, /* 必须 */
        StorageClass: 'STANDARD',
        Body: data.file, // 上传文件对象
        onProgress: (progressData) => {
          this.percentage = JSON.stringify(progressData.percent) * 100
        }
      }, (err, data) => {
        console.log(err || data)
        if (err) {
          this.$message.error('上传失败')
          this.fileList = this.fileList.filter(item => {
            return item.uid !== this.currentUid
          })
          this.isShowProgress = false
        }
        if (!err && data.statusCode === 200) {
          const url = 'https://' + data.Location
          this.fileList = this.fileList.map(item => {
            if (item.uid === this.currentUid) {
              item.url = url
            }
            this.$emit('onSuccess', url)
            this.isShowProgress = false
            return item
          })
        }
      })
    },
    onChange(file, fileList) {
      this.fileList = fileList
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    beforeUpload(file) {
      const MaxSize = 10 * 1024 * 1024
      if (file.size >= MaxSize) {
        this.$message.info('选择的图片尺寸大于2MB')
        return false
      }
      this.currentUid = file.uid
      this.isShowProgress = true
      return true
    }
  }
}
</script>

<style scoped lang="scss">
::v-deep .display .el-upload--picture-card {
  display: none;
}
</style>
